package com.jdzcnc.scan.scan

import android.os.Bundle
import android.view.KeyEvent
import android.widget.ImageButton
import androidx.appcompat.app.AppCompatActivity
import com.jdzcnc.scan.R
import com.journeyapps.barcodescanner.CaptureManager
import com.journeyapps.barcodescanner.DecoratedBarcodeView
import com.journeyapps.barcodescanner.DecoratedBarcodeView.TorchListener


class Scan_2 : AppCompatActivity() {
    private var capture: CaptureManager? = null
    private var ibFlashlight: ImageButton? = null
    private var barcodeScannerView: DecoratedBarcodeView? = null
    private var bTorch = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        //==设置布局、获取控件
        setContentView(R.layout.scan_2)
        barcodeScannerView = findViewById(R.id.dbv)
        ibFlashlight = findViewById(R.id.ib_flashlight_close)

        //==监听： 根据barcodeScannerView设置闪光灯ibFlashlight状态
        barcodeScannerView!!.setTorchListener(object : TorchListener {
            override fun onTorchOn() { //开灯

                //R.drawable.ic_flashlight_open)  开灯显示的图片 自行找图片样式
                ibFlashlight!!.background = resources.getDrawable(R.drawable.ic_flashlight_open)
                bTorch = true
            }

            override fun onTorchOff() { //关灯

                //R.drawable.ic_flashlight_close)  关灯显示的图片 自行找图片样式
                ibFlashlight!!.background = resources.getDrawable(R.drawable.ic_flashlight_close)
                bTorch = false
            }
        })

        //==开或关灯
        ibFlashlight!!.setOnClickListener {
            if (bTorch) {
                barcodeScannerView!!.setTorchOff()
            } else {
                barcodeScannerView!!.setTorchOn()
            }
        }

        //==初始化活动
        capture = CaptureManager(this, barcodeScannerView)
        capture!!.initializeFromIntent(intent, savedInstanceState)
        capture!!.decode()
    }

    override fun onResume() {
        super.onResume()
        capture!!.onResume()
    }

    override fun onPause() {
        super.onPause()
        capture!!.onPause()
        barcodeScannerView!!.setTorchOff()
    }

    override fun onDestroy() {
        super.onDestroy()
        capture!!.onDestroy()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        capture!!.onSaveInstanceState(outState)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        capture!!.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return barcodeScannerView!!.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event)
    }
}